package com.harveyspace.aes.social.utils;

import com.google.gson.JsonObject;
import com.harveyspace.aes.core.utils.JsonUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Token工具类
 *
 * @Author <a href="harveyer@163.com">harvey</a>
 * @date 2018/2/9
 */
public class TokenUtil {

	private static Matcher matcher = null;
    
	/**
	 * 参考自 qq sdk
	 * 
	 * @param result 从字符串中获取accessToken
	 * @return String 返回类型
	 */
	public static String getAccessToken(String result) {
		String accessToken = "";
		try {
		    JsonObject json = JsonUtil.toJsonObject(result);
		            
			if (null != json) {
				accessToken = JsonUtil.getString(json, "access_token");
			}
		} catch (Exception e) {
			matcher = Pattern.compile("^access_token=(\\w+)&expires_in=(\\w+)&refresh_token=(\\w+)$").matcher(result);
			if (matcher.find()) {
				accessToken = matcher.group(1);
			} else {
				matcher = Pattern.compile("^access_token=(\\w+)&expires_in=(\\w+)$").matcher(result);
				if (matcher.find()) {
					accessToken = matcher.group(1);
				}
			}
		}
		return accessToken;
	}
	
	/**
	 * 匹配QQ openid
	 * 
	 * @param string 字符串
	 * @return String openid
	 */
	public static String getOpenId(String string) {
		String openid = null;
		matcher = Pattern.compile("\"openid\"\\s*:\\s*\"(\\w+)\"").matcher(string);
		if (matcher.find()) {
			openid = matcher.group(1);
		}
		return openid;
	}
	
}
